#!/usr/bin/python
# -*- coding: utf-8 -*-
# encoding: utf-8

'''
Provide user specific data and interact with gate.io
'''
from manager.models import *
from gate.gateAPI import GateIO

## 填写 apiKey APISECRET
apiKey = 'your api key'
secretKey = 'your api secret'
## address
btcAddress = 'your btc address'


## Provide constants

API_QUERY_URL = 'data.gateio.io'
API_TRADE_URL = 'api.gateio.io'

## Create a gate class instance

gate_query = GateIO(API_QUERY_URL, apiKey, secretKey)
gate_trade = GateIO(API_TRADE_URL, apiKey, secretKey)


# Trading Pairs
# print(gate_query.pairs())
# 交易历史 成交记录
def get_pair_market():
    result_dic = gate_query.marketinfo()
    if result_dic['result'] == 'true':
        result_diclist = result_dic['pairs']
        pair_list = []
        for market_dic in result_diclist:
            for name, dic in market_dic.items():
                pair = GatePair(name)
                pair.__dict__.update(dic)
                pair_list.append(pair)
        return pair_list
    else:
        return []


# 交易历史 成交记录
def get_tradeHistory_list(pair_name, trade_id = 0):
    '''
    :param pair_name: 配对名
    :param trade_id: 记录 id
    :return: 交易历史 成交记录
    '''
    # try:
    #     result_dic = gate_query.tradeHistory(
    #         '%s/%d' % (pair_name, trade_id)) if trade_id != 0 else gate_query.tradeHistory(pair_name)
    #     if result_dic['result'] == 'true':
    #         result_diclist = result_dic['data']
    #         trade_list = []
    #         for trade_dic in result_diclist:
    #             trade = GateTrade()
    #             trade.__dict__.update(trade_dic)
    #             trade.pair = pair_name
    #             trade_list.append(trade)
    #         return trade_list
    #     else:
    #         return []
    # except Exception as e:
    #     print('ERROR:', e)
    #     return []

# 交易 Kline
def get_kline_list(pair_name, group_sec=60, range_hour=1):
    '''
    :param pair_name: 配对名
    :param trade_id: 记录 id
    :return: 交易历史 成交记录
    '''

    param = '%s?group_sec=%d&range_hour=%d' % (pair_name, group_sec, range_hour)
    result_dic = gate_query.klineList(param)
    if result_dic['result'] == 'true':
        result_diclist = result_dic['data']
        kline_list = []
        for kline_dic in result_diclist:
            # dic = {
            #     "timestamp":kline_dic[0],
            #     "volume":kline_dic[1],
            #     "close":kline_dic[2],
            #     "high":kline_dic[3],
            #     "low":kline_dic[4],
            #     "open":kline_dic[5]
            # }
            kline = GateKline(pair_name=pair_name,
                              group_sec=group_sec,
                              range_hour=range_hour)
            kline.set_timestamp(int(kline_dic[0])/1000)#.timestamp = int(kline_dic[0])/1000
            kline.volume = float(kline_dic[1])
            kline.close = float(kline_dic[2])
            kline.high = float(kline_dic[3])
            kline.low = float(kline_dic[4])
            kline.open = float(kline_dic[5])
            kline_list.append(kline)
        return kline_list
    else:
        return []
    # try:
    #     param = '%s?group_sec=%d&range_hour=%d' % (pair_name, group_sec, range_hour)
    #     result_dic = gate_query.klineList(param)
    #     if result_dic['result'] == 'true':
    #         result_diclist = result_dic['data']
    #         kline_list = []
    #         for kline_dic in result_diclist:
    #             kline = GateKline(pair_name=pair_name,
    #                               group_sec=group_sec,
    #                               range_hour=range_hour)
    #             kline.time = int(kline_dic[0])
    #             kline.volume = float(kline_dic[1])
    #             kline.close = float(kline_dic[2])
    #             kline.high = float(kline_dic[3])
    #             kline.low = float(kline_dic[4])
    #             kline.open = float(kline_dic[5])
    #             kline_list.append(kline)
    #         return kline_list
    #     else:
    #         return []
    # except Exception as e:
    #     print('ERROR:', e)
    # return []




## Below, use general methods that query the exchange

#  Market Info
# print(gate_query.marketinfo())

# Market Details
# print(gate_query.marketlist())

# Tickers
# print(gate_query.tickers())
# Depth
# print(gate_query.orderBooks())

# orders
# print(gate_query.openOrders())


## Below, use methods that make use of the users keys

# Ticker
# print(gate_query.ticker('btc_usdt'))

# Market depth of pair
# print(gate_query.orderBook('btc_usdt'))

# Trade History
# print(gate_query.tradeHistory('btc_usdt'))

# Get account fund balances
# print(gate_trade.balances())

# get new address
# print(gate_trade.depositAddres('btc'))

# get deposit withdrawal history
# print(gate_trade.depositsWithdrawals('1469092370', '1569092370'))

# Place order sell
# print(gate_trade.buy('etc_btc', '0.001', '123'))

# Place order sell
# print(gate_trade.sell('etc_btc', '0.001', '123'))

# Cancel order
# print(gate_trade.cancelOrder('267040896', 'etc_btc'))

# Cancel all orders
# print(gate_trade.cancelAllOrders('0', 'etc_btc'))

# Get order status
# print(gate_trade.getOrder('267040896', 'eth_btc'))

# Get my last 24h trades
# print(gate_trade.mytradeHistory('etc_btc', '267040896'))

# withdraw
# print(gate_trade.withdraw('btc', '88', btcAddress))
